//
//  XYBookMarkModel.swift
//  XYReadBook
//
//  Created by fox on 2018/1/1.
//  Copyright © 2018年 tsaievan. All rights reserved.
//

import UIKit
import FMDB

/// 一本书的信息
class XYBookMark: NSObject {
    var body:String
    var title:String
    var time:String
    var chapterIndex:Int
    init(body:String,title:String,time:String,chapterIndex:Int) {
        self.body = body
        self.title = title
        self.time = time
        self.chapterIndex = chapterIndex
        super.init()
    }
}
/// 书签数据库管理类    2018/1/1
class XYBookMarkModel: NSObject {
    /// 创建表
  class  func createTable() {
    let sql = "CREATE TABLE IF NOT EXISTS t_bookMark(title text NOT NULL,body text NOT NULL,time text NOT NULL,chapterIndex INTEGER NOT NULL,PRIMARY KEY('body'))"
        if !FileManager.default.fileExists(atPath: DBManager.shared.pathToDatabase) {
             DBManager.shared.database = FMDatabase(path: DBManager.shared.pathToDatabase!)
            if DBManager.shared.database.open() {
                do {
                    try
                        DBManager.shared.database.executeUpdate(sql, values: nil)
                        XYLog(messsage: "创建表成功")
                        XYLog(messsage: DBManager.shared.pathToDatabase)
                } catch {
                    XYLog(messsage: "创建表失败")
                    print(error.localizedDescription)
                }
                 DBManager.shared.database.close()
            } else {
                XYLog(messsage: "没有打开数据库")
            }
        }
    }

    // XWJ failure: @escaping (Error?)->())
    static  func insertBookChater(book:XYBookMark,success:((Bool)->()),failure: (Error)->()) {
        if self.openDatabase() {
            do {

                // 字符串过滤
                var query = ""
                let newBody = book.body.replacingCharacters(pattern: "\n", template: "")
                query += "insert into 't_bookMark'('title','body','time','chapterIndex') values ('\(book.title)','\(newBody)','\(book.time)','\(book.chapterIndex)')"

                if DBManager.shared.database.executeStatements(query) {
                    success(true)
                }else {
                    failure(DBManager.shared.database.lastError())
                }
            }
            DBManager.shared.database.close()
        }

        XYLog(messsage: DBManager.shared.pathToDatabase)
    }


    static func loadBooks() -> [XYBookMark] {
        // 返回数据模型
        let sqlStr = "select *, rowid NAVICAT_ROWID from t_bookMark  limit 0,1000"

        var books:[XYBookMark] = []
        if openDatabase() {
            do {
                do{
                    let rs = try DBManager.shared.database.executeQuery(sqlStr, values: nil)
                    while rs.next() {
                    let title = rs.string(forColumn: "title")
                     let body = rs.string(forColumn: "body")
                     let time = rs.string(forColumn: "time")
                     let chapterIndex = rs.string(forColumn: "chapterIndex")

                        let book = XYBookMark.init(body: body ?? "", title: title ?? "", time: time ?? "", chapterIndex: (chapterIndex ?? "0").integerValue() )
                        books.append(book)
                    }
                }catch{
                    return books
                }
            }
        }
             return books
    }


    static  func openDatabase() -> Bool {
        if DBManager.shared.database == nil {
            if FileManager.default.fileExists(atPath: DBManager.shared.pathToDatabase) {
                DBManager.shared.database = FMDatabase(path: DBManager.shared.pathToDatabase)
            }
        }

        if DBManager.shared.database != nil {
            if DBManager.shared.database.open() {
                return true
            }
        }
        return false
    }

    static func remove(body:String,success:((Bool)->()),failure: (Error)->()) {
        //vue
          let newBody = body.replacingCharacters(pattern: "\n", template: "")
      let sql =  String.init(format: "DELETE FROM t_bookMark where body='%@'", newBody)

        if openDatabase() {
            do{
              try  DBManager.shared.database.executeUpdate(sql, values: [newBody])
                   DBManager.shared.database.close()
                success(true)
            }catch {
                failure(DBManager.shared.database.lastError())
            }
        }

    }

    static func containsBody(body:String) -> Bool {
        if openDatabase() {
            //  select * from t_bookMark where title='冰火两重天'
            let newBody = body.replacingCharacters(pattern: "\n", template: "")
            let query = String.init(format: "select * from t_bookMark where body='%@'", newBody)
                /// 返回查询结果
            do {
                let result = try DBManager.shared.database.executeQuery(query, values: nil)
                while result.next() {
                  let str =  result.string(forColumn: "body")
                    if let str = str {
                        if str.length > 0 {
                            return true
                        }
                    }
                }
            } catch {
                XYLog(messsage: "失败了")
            }
             DBManager.shared.database.close()
            /// 关闭数据库
        }
        return false
    }
}
